package serialport;

import android.util.Log;

public class Serialport {
    public static  class Baudrate {
            public static final int B57600 =0010001;
            public static final int B115200= 0010002;
            public static final int B230400= 0010003;
            public static final int B460800= 0010004;
            public static final int B500000= 0010005;
            public static final int B576000= 0010006;
            public static final int B921600= 0010007;
            public static final int B1000000= 0010010;
            public static final int B1152000= 0010011;
            public static final int B1500000= 0010012;
            public static final int B2000000= 0010013;
            public static final int B2500000= 0010014;
            public static final int B3000000= 0010015;
            public static final int B3500000= 0010016;
            public static final int B4000000= 0010017;
    };

    private static boolean loopRead;

    public interface ReadCallback{
        void onData(byte[] bytes,long len);
    }
    static {
        System.loadLibrary("serial_port");
    }
    public static native boolean open(String pathSerialport, int baudrate);
    private static native int close();
    public static native long read(byte[] buff,long len);
    public static native long write(byte[] buff,long len);
    public static boolean startLoopRead(boolean open, final ReadCallback readCallback){
        if(open){
            loopRead=true;
            new Thread(){
                @Override
                public void run() {
                    while (loopRead){
                        byte[] buff=new byte[10];
                        long count=read(buff,buff.length);
                        if(count>0){
                            readCallback.onData(buff,count);
                        }
                    }

                }
            }.start();
        }
        return open;
    }
    public static void closeSerialport(){
            int res=close();
            Log.d("closeSerialport",Integer.toString(res));
            loopRead=false;

    }
}
